package com.css.zfzx.sjcj.modules.hddcRSInterpretationPolygon.service.impl;

import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.result.ExcelImportResult;
import com.alibaba.fastjson.JSONObject;
import com.css.bpm.platform.api.local.PlatformAPI;
import com.css.bpm.platform.sys.dict.repository.entity.DictItemEntity;
import com.css.bpm.platform.utils.*;
import com.css.zfzx.sjcj.common.spacedata.vo.SpaceDataParamsVo;
import com.css.zfzx.sjcj.common.utils.EasyPoiExcelUtil;
import com.css.zfzx.sjcj.common.utils.UpdateUtil;
import com.css.zfzx.sjcj.modules.hddcGeologicalSvyPlanningLine.repository.entity.HddcGeologicalsvyplanninglineEntity;
import com.css.zfzx.sjcj.modules.hddcRSInterpretationPolygon.repository.HddcRsinterpretationpolygonNativeRepository;
import com.css.zfzx.sjcj.modules.hddcRSInterpretationPolygon.repository.HddcRsinterpretationpolygonRepository;
import com.css.zfzx.sjcj.modules.hddcRSInterpretationPolygon.repository.entity.HddcRsinterpretationpolygonEntity;
import com.css.zfzx.sjcj.modules.hddcRSInterpretationPolygon.service.HddcRsinterpretationpolygonService;
import com.css.zfzx.sjcj.modules.hddcRSInterpretationPolygon.viewobjects.HddcRsinterpretationpolygonQueryParams;
import com.css.zfzx.sjcj.modules.hddcRSInterpretationPolygon.viewobjects.HddcRsinterpretationpolygonVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.util.*;

/**
 * @author zhangping
 * @date 2020-11-30
 */
@Service
public class HddcRsinterpretationpolygonServiceImpl implements HddcRsinterpretationpolygonService {

	@Autowired
    private HddcRsinterpretationpolygonRepository hddcRsinterpretationpolygonRepository;
    @Autowired
    private HddcRsinterpretationpolygonNativeRepository hddcRsinterpretationpolygonNativeRepository;

    @Override
    public JSONObject queryHddcRsinterpretationpolygons(HddcRsinterpretationpolygonQueryParams queryParams, int curPage, int pageSize,String sort,String order) {
        Page<HddcRsinterpretationpolygonEntity> hddcRsinterpretationpolygonPage = this.hddcRsinterpretationpolygonNativeRepository.queryHddcRsinterpretationpolygons(queryParams, curPage, pageSize, sort, order);
        JSONObject jsonObject = PlatformPageUtils.formatPageData(hddcRsinterpretationpolygonPage);
        return jsonObject;
    }


    @Override
    public HddcRsinterpretationpolygonEntity getHddcRsinterpretationpolygon(String id) {
        HddcRsinterpretationpolygonEntity hddcRsinterpretationpolygon = this.hddcRsinterpretationpolygonRepository.findById(id).orElse(null);
         return hddcRsinterpretationpolygon;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public HddcRsinterpretationpolygonEntity saveHddcRsinterpretationpolygon(HddcRsinterpretationpolygonEntity hddcRsinterpretationpolygon) {
        String uuid = UUIDGenerator.getUUID();
        hddcRsinterpretationpolygon.setUuid(uuid);
        hddcRsinterpretationpolygon.setCreateUser(PlatformSessionUtils.getUserId());
        hddcRsinterpretationpolygon.setCreateTime(PlatformDateUtils.getCurrentTimestamp());
        hddcRsinterpretationpolygon.setIsValid("1");
        hddcRsinterpretationpolygon.setQualityinspectionStatus("0");
        hddcRsinterpretationpolygon.setExtends10("1");
        this.hddcRsinterpretationpolygonRepository.save(hddcRsinterpretationpolygon);
        return hddcRsinterpretationpolygon;
    }
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Iterable<HddcRsinterpretationpolygonEntity> saveHddcRsinterpretationpolygonList(List<HddcRsinterpretationpolygonEntity> list) {
        for (HddcRsinterpretationpolygonEntity hddcRsinterpretationpolygon : list) {
            String uuid = UUIDGenerator.getUUID();
            hddcRsinterpretationpolygon.setUuid(uuid);
            hddcRsinterpretationpolygon.setCreateUser(PlatformSessionUtils.getUserId());
            hddcRsinterpretationpolygon.setCreateTime(PlatformDateUtils.getCurrentTimestamp());
            hddcRsinterpretationpolygon.setIsValid("1");
            hddcRsinterpretationpolygon.setQualityinspectionStatus("0");
            hddcRsinterpretationpolygon.setExtends10("1");
        }

        return hddcRsinterpretationpolygonNativeRepository.batchSave(list);
    }
    @Override
    @Transactional(rollbackFor = Exception.class)
    public HddcRsinterpretationpolygonEntity updateHddcRsinterpretationpolygon(HddcRsinterpretationpolygonEntity hddcRsinterpretationpolygon) {
        HddcRsinterpretationpolygonEntity entity = hddcRsinterpretationpolygonRepository.findById(hddcRsinterpretationpolygon.getUuid()).get();
        UpdateUtil.copyNullProperties(entity,hddcRsinterpretationpolygon);
        hddcRsinterpretationpolygon.setUpdateUser(PlatformSessionUtils.getUserId());
        hddcRsinterpretationpolygon.setUpdateTime(PlatformDateUtils.getCurrentTimestamp());
        this.hddcRsinterpretationpolygonRepository.save(hddcRsinterpretationpolygon);
        return hddcRsinterpretationpolygon;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteHddcRsinterpretationpolygons(List<String> ids) {
        List<HddcRsinterpretationpolygonEntity> hddcRsinterpretationpolygonList = this.hddcRsinterpretationpolygonRepository.findAllById(ids);
        if(!PlatformObjectUtils.isEmpty(hddcRsinterpretationpolygonList) && hddcRsinterpretationpolygonList.size() > 0) {
            for(HddcRsinterpretationpolygonEntity hddcRsinterpretationpolygon : hddcRsinterpretationpolygonList) {
                hddcRsinterpretationpolygon.setUpdateUser(PlatformSessionUtils.getUserId());
                hddcRsinterpretationpolygon.setUpdateTime(PlatformDateUtils.getCurrentTimestamp());
                hddcRsinterpretationpolygon.setIsValid("0");
                this.hddcRsinterpretationpolygonRepository.save(hddcRsinterpretationpolygon);
            }
        }
    }

    /**
     * 逻辑删除-根据项目id删除数据
     * @param projectIds
     */
    @Override
    public void deleteByProjectId(List<String> projectIds) {
        List<HddcRsinterpretationpolygonEntity> hddcRsinterpretationpolygonList = this.hddcRsinterpretationpolygonRepository.queryHddcRsinterpretationpolygonsByProjectId(projectIds);
        if(!PlatformObjectUtils.isEmpty(hddcRsinterpretationpolygonList) && hddcRsinterpretationpolygonList.size() > 0) {
            for(HddcRsinterpretationpolygonEntity hddcRsinterpretationpolygon : hddcRsinterpretationpolygonList) {
                hddcRsinterpretationpolygon.setUpdateUser(PlatformSessionUtils.getUserId());
                hddcRsinterpretationpolygon.setUpdateTime(PlatformDateUtils.getCurrentTimestamp());
                hddcRsinterpretationpolygon.setIsValid("0");
                this.hddcRsinterpretationpolygonRepository.save(hddcRsinterpretationpolygon);
            }
        }
    }

    /**
     * 逻辑删除-根据任务id删除数据
     * @param taskId
     */
    @Override
    public void deleteByTaskId(List<String> taskId) {
        List<HddcRsinterpretationpolygonEntity> hddcRsinterpretationpolygonList = this.hddcRsinterpretationpolygonRepository.queryHddcRsinterpretationpolygonsByTaskId(taskId);
        if(!PlatformObjectUtils.isEmpty(hddcRsinterpretationpolygonList) && hddcRsinterpretationpolygonList.size() > 0) {
            for(HddcRsinterpretationpolygonEntity hddcRsinterpretationpolygon : hddcRsinterpretationpolygonList) {
                hddcRsinterpretationpolygon.setUpdateUser(PlatformSessionUtils.getUserId());
                hddcRsinterpretationpolygon.setUpdateTime(PlatformDateUtils.getCurrentTimestamp());
                hddcRsinterpretationpolygon.setIsValid("0");
                this.hddcRsinterpretationpolygonRepository.save(hddcRsinterpretationpolygon);
            }
        }
    }

    @Override
    public String judegeParams(String[] datas) {
        String str = "";
        Set<String> set = new HashSet<String>(Arrays.asList(datas));
        if(!set.contains("ID")){
            str+="ID,";
        }
        if(!set.contains("GeomorphyCode")){
            str+="GeomorphyCode,";
        }
        if(!set.contains("GeomorphyType")){
            str+="GeomorphyType,";
        }
        if(!set.contains("GeomorphyName")){
            str+="GeomorphyName,";
        }
        if(!set.contains("GeomorphyAccording")){
            str+="GeomorphyAccording,";
        }
        if(!set.contains("CommentInfo")){
            str+="CommentInfo,";
        }
        return str;
    }

    @Override
    public void saveHddcRsinterpretationpolygonFromShpFiles(List<List<Object>> list, String provinceName, String cityName, String areaName,String savefilename) {
        if(list!=null&&list.size()>0){
            List<HddcRsinterpretationpolygonEntity> datas= new ArrayList<>();
            for(int i=0;i<list.size();i++){
                List<Object> obs=list.get(i);
                HddcRsinterpretationpolygonEntity data = new HddcRsinterpretationpolygonEntity();
                data.setArea(areaName);
                data.setProvince(provinceName);
                data.setCity(cityName);
                data.setExtends8(savefilename);
                data.setId(obs.get(1).toString());
                data.setGeomorphycode(obs.get(2).toString());
                data.setGeomorphytype(obs.get(3).toString());
                data.setGeomorphyname(obs.get(4).toString());
                data.setGeomorphyaccording(obs.get(5).toString());
                data.setCommentInfo(obs.get(6).toString());
                data.setExtends16("CGCS2000");
                String pstr=obs.get(0).toString();
                /*String[] ss1=pstr.split("\\(");
                if(ss1.length>=2){
                    String[] ss2=ss1[ss1.length-1].split("\\)");
                    if(ss2.length<=2){
                        String spacedata=ss2[0].replace(",",";").replace("; ",";").replace(" ",",");
                        data.setExtends5(spacedata);
                    }
                }*/
                pstr = pstr.replace(")), ((", "#");
                pstr = pstr.replace("), (", "#");
                String[] ss1=pstr.split("\\(");
                if(ss1.length>=2){
                    String[] ss2=ss1[ss1.length-1].split("\\)");
                    if(ss2.length<=2){
                        String spacedata=ss2[0].replace(",",";").replace("; ",";").replace(" ",",");
                        data.setExtends5(spacedata);
                    }
                }
                datas.add(data);
                /*for(int j=0;j<obs.size();j++){
                    Object value=obs.
                }*/
            }
            deleteByCreateUser(provinceName,cityName,areaName);

            saveHddcRsinterpretationpolygonList(datas);
        }
    }

    @Override
    public List<HddcRsinterpretationpolygonEntity> findAll() {
        List<HddcRsinterpretationpolygonEntity> list=this.hddcRsinterpretationpolygonRepository.findAll();
        return list;
    }

    @Override
    @Transactional
    public void deleteFileData(SpaceDataParamsVo paramsVo) {
        String provinceName=paramsVo.getProvinceName();
        String cityName=paramsVo.getCityName();
        String areaName=paramsVo.getAreaName();
        String savefilename=paramsVo.getSavefilename();
        hddcRsinterpretationpolygonRepository.deleteFileData(provinceName,cityName,areaName,savefilename);
    }

    public void deleteByCreateUser(String provinceName,String cityName,String areaName){
        String createID=PlatformSessionUtils.getUserId();
        List<HddcRsinterpretationpolygonEntity> hddcRsinterpretationpolygonList = this.hddcRsinterpretationpolygonRepository.queryHddcRsinterpretationpolygonByCreateuser(createID,provinceName,cityName,areaName);
        if(!PlatformObjectUtils.isEmpty(hddcRsinterpretationpolygonList) && hddcRsinterpretationpolygonList.size() > 0) {
            hddcRsinterpretationpolygonRepository.deleteAll(hddcRsinterpretationpolygonList);
        }
    }

    @Override
    public List<DictItemEntity> getValidDictItemsByDictCode(String dictCode) {
        List<DictItemEntity> validDictItems = PlatformAPI.getDictAPI().getValidDictItemsByDictCode(dictCode);
        return validDictItems;
    }

    @Override
    public void exportFile(HddcRsinterpretationpolygonQueryParams queryParams, HttpServletResponse response) {
        List<HddcRsinterpretationpolygonEntity> yhDisasterEntities = hddcRsinterpretationpolygonNativeRepository.exportYhDisasters(queryParams);
        List<HddcRsinterpretationpolygonVO> list=new ArrayList<>();
        for (HddcRsinterpretationpolygonEntity entity:yhDisasterEntities) {
            HddcRsinterpretationpolygonVO yhDisasterVO=new HddcRsinterpretationpolygonVO();
            BeanUtils.copyProperties(entity,yhDisasterVO);
            list.add(yhDisasterVO);
        }
        EasyPoiExcelUtil.exportExcel(list, "航、卫片解译面-面", "航、卫片解译面-面", HddcRsinterpretationpolygonVO.class, "航、卫片解译面-面.xls", response);
    }

    @Override
    public String exportExcel(MultipartFile file, HttpServletResponse response) {
        try {
            // 返回的消息
            StringBuilder returnMsg = new StringBuilder();
            // 导入的参数信息
            ImportParams params = new ImportParams();
            // 设置简析的第一行
            params.setHeadRows(1);
            // 是否需要校验
            params.setNeedVerify(true);
            // 获取到Excel数据
            ExcelImportResult<HddcRsinterpretationpolygonVO> result = ExcelImportUtil.importExcelMore(file.getInputStream(), HddcRsinterpretationpolygonVO.class, params);
            List<HddcRsinterpretationpolygonVO> list = result.getList();
            // Excel条数据
            int firstList = list.size();
            StringBuilder sb = new StringBuilder();
            //保存
            saveDisasterList(list, sb);
            returnMsg.append("成功导入" + (result.getList().size() ));
            returnMsg.append(sb);
            if (result.isVerifyFail()) {
                // 校验返回失败行信息
                Iterator<HddcRsinterpretationpolygonVO> iterator = result.getFailList().iterator();
                while (iterator.hasNext()) {
                    HddcRsinterpretationpolygonVO yhDisasterVO = iterator.next();
                    String error = "";
                    returnMsg.append("第" + yhDisasterVO.getRowNum() + "行" + yhDisasterVO.getErrorMsg() + "<br/>");
                    returnMsg.append(error);
                }
            }
            return returnMsg.toString();
        } catch (Exception e) {

            return "导入失败，请检查数据正确性";
        }
    }
    /**
     * 批量存入库表并且返回错误数量
     *
     * @param list
     * @param message
     * @return
     */
    public void saveDisasterList( List<HddcRsinterpretationpolygonVO> list, StringBuilder message) {
        for (int i = 0; i < list.size(); i++) {
            HddcRsinterpretationpolygonEntity yhDisasterEntity = new HddcRsinterpretationpolygonEntity();
            HddcRsinterpretationpolygonVO yhDisasterVO = list.get(i);
            // 将VO数据映射拷贝到库表中
            BeanUtils.copyProperties(yhDisasterVO, yhDisasterEntity);
            saveHddcRsinterpretationpolygon(yhDisasterEntity);
        }
    }

}
